package com.agrishare.controller;

import com.agrishare.entity.Post;
import com.agrishare.entity.Category;
import com.agrishare.entity.User;
import com.agrishare.payload.request.PostRequest;
import com.agrishare.payload.response.MessageResponse;
import com.agrishare.security.services.UserDetailsImpl;
import com.agrishare.service.PostService;
import com.agrishare.service.UserService;
import com.agrishare.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private CategoryService categoryService;
    
    @GetMapping
    public ResponseEntity<Page<Post>> getAllPosts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> posts = postService.findApprovedPosts(pageable);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Post> getPostById(@PathVariable Long id) {
        Optional<Post> post = postService.findById(id);
        if (post.isPresent()) {
            // 增加浏览次数
            postService.incrementViewCount(id);
            return ResponseEntity.ok(post.get());
        }
        return ResponseEntity.notFound().build();
    }
    
    @PostMapping
    @PreAuthorize("hasRole('USER') or hasRole('EXPERT') or hasRole('ADMIN')")
    public ResponseEntity<?> createPost(@Valid @RequestBody PostRequest postRequest,
                                        Authentication authentication) {
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Optional<User> user = userService.findById(userDetails.getId());
        Optional<Category> category = categoryService.findById(postRequest.getCategoryId());
        
        if (!user.isPresent()) {
            return ResponseEntity.badRequest().body(new MessageResponse("用户不存在"));
        }
        
        if (!category.isPresent()) {
            return ResponseEntity.badRequest().body(new MessageResponse("分类不存在"));
        }
        
        Post post = new Post(postRequest.getTitle(), postRequest.getContent(), 
                            user.get(), category.get());
        
        // 专家和管理员发帖自动审核通过
        if (userDetails.getAuthorities().stream()
                .anyMatch(auth -> auth.getAuthority().equals("ROLE_EXPERT") || 
                                 auth.getAuthority().equals("ROLE_ADMIN"))) {
            post.setIsApproved(true);
        }
        
        Post savedPost = postService.createPost(post);
        return ResponseEntity.ok(savedPost);
    }
    
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('EXPERT') or hasRole('ADMIN')")
    public ResponseEntity<?> updatePost(@PathVariable Long id,
                                        @Valid @RequestBody PostRequest postRequest,
                                        Authentication authentication) {
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Optional<Post> postOpt = postService.findById(id);
        
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Post post = postOpt.get();
        
        // 检查权限：只有作者或管理员可以编辑
        if (!post.getAuthor().getId().equals(userDetails.getId()) &&
            !userDetails.getAuthorities().stream()
                    .anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"))) {
            return ResponseEntity.status(403).body(new MessageResponse("无权限编辑此帖子"));
        }
        
        post.setTitle(postRequest.getTitle());
        post.setContent(postRequest.getContent());
        
        if (postRequest.getCategoryId() != null) {
            Optional<Category> category = categoryService.findById(postRequest.getCategoryId());
            if (category.isPresent()) {
                post.setCategory(category.get());
            }
        }
        
        Post updatedPost = postService.updatePost(post);
        return ResponseEntity.ok(updatedPost);
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('EXPERT') or hasRole('ADMIN')")
    public ResponseEntity<?> deletePost(@PathVariable Long id,
                                        Authentication authentication) {
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        Optional<Post> postOpt = postService.findById(id);
        
        if (!postOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Post post = postOpt.get();
        
        // 检查权限：只有作者或管理员可以删除
        if (!post.getAuthor().getId().equals(userDetails.getId()) &&
            !userDetails.getAuthorities().stream()
                    .anyMatch(auth -> auth.getAuthority().equals("ROLE_ADMIN"))) {
            return ResponseEntity.status(403).body(new MessageResponse("无权限删除此帖子"));
        }
        
        postService.deletePost(id);
        return ResponseEntity.ok(new MessageResponse("帖子删除成功"));
    }
    
    @GetMapping("/search")
    public ResponseEntity<Page<Post>> searchPosts(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> posts = postService.searchPosts(keyword, pageable);
        return ResponseEntity.ok(posts);
    }
    
    @GetMapping("/category/{categoryId}")
    public ResponseEntity<Page<Post>> getPostsByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        Optional<Category> category = categoryService.findById(categoryId);
        if (!category.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Post> posts = postService.findPostsByCategory(category.get(), pageable);
        return ResponseEntity.ok(posts);
    }
    
    @PostMapping("/{id}/approve")
    @PreAuthorize("hasRole('EXPERT') or hasRole('ADMIN')")
    public ResponseEntity<?> approvePost(@PathVariable Long id) {
        postService.approvePost(id);
        return ResponseEntity.ok(new MessageResponse("帖子审核通过"));
    }
    
    @PostMapping("/{id}/pin")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> pinPost(@PathVariable Long id) {
        postService.pinPost(id);
        return ResponseEntity.ok(new MessageResponse("帖子置顶成功"));
    }
    
    @PostMapping("/{id}/feature")
    @PreAuthorize("hasRole('EXPERT') or hasRole('ADMIN')")
    public ResponseEntity<?> featurePost(@PathVariable Long id) {
        postService.featurePost(id);
        return ResponseEntity.ok(new MessageResponse("帖子加精成功"));
    }
}